package cn.cdqf.manager.util;

import cn.cdqf.coupon.util.IdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executor;

@Component
@SuppressWarnings("all")
public class CouponCodeUtil {

    @Autowired
    private IdUtils idUtils;
    @Autowired
    private Executor getAsyncExecutor;
    //要生成多少个优惠券码就要开多少个线程
    public  List<String> generate(int count,String id){
        CopyOnWriteArrayList<String> objects = new CopyOnWriteArrayList<>();
        int halfCount = count / 2;
        CompletableFuture<Void> arrayListCompletableFuture = CompletableFuture.runAsync(() -> {

            for (int i = 0; i < halfCount; i++) {
                //生成id
                objects.add(idUtils.getIdNoAsync(id));
            }
        },getAsyncExecutor);
        CompletableFuture<Void> arrayListCompletableFuture2 = CompletableFuture.runAsync(() -> {

            for (int i = 0; i < count-halfCount; i++) {
                //生成id
                objects.add(idUtils.getIdNoAsync(id));
            }
        },getAsyncExecutor);
         CompletableFuture.allOf(arrayListCompletableFuture, arrayListCompletableFuture2).join();
        return objects;
    }
}
